import pymysql

from config import book_id


#定义数据集工具类
class DBTools(object):

    # 创建连接类方法
    @classmethod
    def __creat_conn(cls):
        conn=pymysql.connect(host="192.168.190.130",port=3306,user="root",password="123456",
                             charset="utf8",database="test_db")
        return conn
    #查询一条记录，类方法
    @classmethod
    def query_one(cls,sql):
        conn = None
        my_cursor = None
        resp=None
        try:
            #创建连接
            conn= DBTools.__creat_conn()
            #创建游标
            my_cursor=conn.cursor()
            #执行sql
            my_cursor.execute(sql)
            #接收一条记录
            resp = my_cursor.fetchall()
        except Exception as e:
            print("执行失败",e)
        finally:
            #关闭游标
            my_cursor.close()
            #关闭连接
            conn.close()
            return resp
    #增删改操作
    @classmethod
    def ab_iud(cls,sql):
        conn = None
        my_cursor = None
        try:
            #创建连接
            conn= DBTools.__creat_conn()
            #创建游标
            my_cursor=conn.cursor()
            #执行sql
            my_cursor.execute(sql)
            print("affected_row:",conn.affected_rows())
            #提交事务
            conn.commit()

        except Exception as e:
            print("执行失败",e)
            #回滚事务
            conn.rollback()
        finally:
            #关闭游标
            my_cursor.close()
            #关闭连接
            conn.close()
if __name__ == '__main__':
    result= DBTools.query_one("select * from t_book;")
    print(result)
    # DBTools.ab_iud(f"delete from t_book where id={book_id};")
    # DBTools.ab_iud("insert into t_book (id,title,readnum) values(9,'东游记',1000);")
    DBTools.ab_iud(f"delete from t_book where id=7;")





